package com.exwave.socialgame.jwt_token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.exwave.socialgame.model_user.entity.User;

import org.springframework.stereotype.Service;

import java.util.Date;

@Service("tokenService")
public class TokenServiceImpl implements TokenService {
    @Override
    public String getToken(User user) {
        String token = "";
        token = JWT.create()
                .withAudience(String.valueOf(user.getUid()))
                .withIssuedAt(new Date()) //签发时间，用于手动判断过期否
                .withExpiresAt(new Date(System.currentTimeMillis() + 3600 * 72))//过期时间,三天
                .sign(Algorithm.HMAC256(user.getUpassword())); //加密
        return token;
    }

    /**
     * 通过token获取uid
     */
    @Override
    public int getUidByToken(String token) {
        String userId;
        userId = JWT.decode(token).getAudience().get(0);
        return Integer.parseInt(userId);
    }

    /**
     * 获取签发时间
     */
    @Override
    public Date getSignTime(String token) {
        Date date = JWT.decode(token).getIssuedAt();
        return date;
    }
}
